import { execSync } from 'child_process';
import fs from 'fs';
import { mergeTranslations } from './merge-translations.js';

console.log('🚀 Starting i18n workflow...\n');

try {
  // 1. 运行 i18next-scanner
  console.log('1. Running i18next-scanner...');
  execSync('npm run i18n:scan', { stdio: 'inherit' });
  
  // 2. 运行 TypeScript 提取器
  console.log('\n2. Running TypeScript extractor...');
  execSync('npm run i18n:tsextract', { stdio: 'inherit' });
  
  // 3. 合并和清理翻译文件
  console.log('\n3. Merging and cleaning translation files...');
  // 使用我们的合并逻辑保留现有翻译
  console.log('Preserving existing translations and adding new keys...');
  
  // 读取现有翻译文件
  const enTranslations = JSON.parse(fs.readFileSync('./src/i18n/locales/en/translation.json', 'utf-8'));
  const zhTranslations = JSON.parse(fs.readFileSync('./src/i18n/locales/zh/translation.json', 'utf-8'));
  
  // 使用合并逻辑处理文件（保留现有翻译）
  const processedEnTranslations = mergeTranslations(enTranslations, enTranslations);
  const processedZhTranslations = mergeTranslations(zhTranslations, zhTranslations);
  
  // 保存处理后的文件
  fs.writeFileSync('./src/i18n/locales/en/translation.json', JSON.stringify(processedEnTranslations, null, 2));
  fs.writeFileSync('./src/i18n/locales/zh/translation.json', JSON.stringify(processedZhTranslations, null, 2));
  
  console.log('\n✅ i18n workflow completed successfully!');
  console.log('\n📝 Next steps:');
  console.log('1. Check the updated translation files in src/i18n/locales/');
  console.log('2. Fill in missing translations in the Chinese file');
  console.log('3. Run the ESLint plugin to catch any remaining hardcoded strings');
  
} catch (error) {
  console.error('❌ Error in i18n workflow:', error.message);
  process.exit(1);
}